package com.luanye.enjoy.consumer;

import com.alibaba.fastjson.JSON;
import com.luanye.enjoy.dao.*;
import com.luanye.enjoy.dto.*;
import com.luanye.enjoy.entity.*;
import com.luanye.enjoy.utils.BeanCopyUtils;
import lombok.AllArgsConstructor;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

import static com.luanye.enjoy.constants.MQConst.MAXWELL_QUEUE;

@Component
@RabbitListener(queues = MAXWELL_QUEUE)
@AllArgsConstructor
public class MaxWellConsumer {

    private final BaiKeElasticSearchDao baiKeElasticSearchDao;

    private final DynamicElasticSearchDao dynamicElasticSearchDao;

    private final PolicyElasticSearchDao policyElasticSearchDao;

    private final RecipeElasticSearchDao recipeElasticSearchDao;

    private final WikiElasticSearchDao wikiElasticSearchDao;

    @RabbitHandler
    public void process( byte[] data ){
        MaxwellDataDTO maxwellDataDTO = null;
        try {
            maxwellDataDTO = JSON.parseObject(new String(data, "utf8"), MaxwellDataDTO.class);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        if (maxwellDataDTO.getType().equals("insert") || maxwellDataDTO.getType().equals("update")){
            switch (maxwellDataDTO.getTable()){
                case "enjoy_baike":
                    BaikeTO baikeTO = JSON.parseObject(JSON.toJSONString(maxwellDataDTO.getData()), BaikeTO.class);
                    baiKeElasticSearchDao.save(BeanCopyUtils.copyBean(baikeTO, BaiKeSearchDTO.class));
                    break;
                case "enjoy_policy":
                    PolicyTO policyTO = JSON.parseObject(JSON.toJSONString(maxwellDataDTO.getData()), PolicyTO.class);
                    policyElasticSearchDao.save(BeanCopyUtils.copyBean(policyTO, PolicySearchDTO.class));
                    break;
                case "enjoy_recipe":
                    RecipeTO recipeTO = JSON.parseObject(JSON.toJSONString(maxwellDataDTO.getData()), RecipeTO.class);
                    recipeElasticSearchDao.save(BeanCopyUtils.copyBean(recipeTO, RecipeSearchDTO.class));
                    break;
                case "enjoy_dynamic":
                    DynamicTO dynamic = JSON.parseObject(JSON.toJSONString(maxwellDataDTO.getData()), DynamicTO.class);
                    dynamicElasticSearchDao.save(BeanCopyUtils.copyBean(dynamic, DynamicSearchDTO.class));
                    break;
                case "enjoy_wikipedia":
                    WikipediaTO wikipedia = JSON.parseObject(JSON.toJSONString(maxwellDataDTO.getData()), WikipediaTO.class);
                    wikiElasticSearchDao.save(BeanCopyUtils.copyBean(wikipedia, WikiSearchDTO.class));
                    break;

            }
        }
    }
}
